package com.shalanzi.hospital.interceptor;

import com.shalanzi.hospital.exceptions.NoLoginException;
import com.shalanzi.hospital.mapper.UserMapper;
import com.shalanzi.hospital.utils.LoginUserUtil;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Dream_飞翔
 * @date 2021/9/13
 * @time 9:48
 * @email 1072876976@qq.com
 */
// 非法访问拦截
public class NoLoginInterceptor extends HandlerInterceptorAdapter {
    @Resource
    private UserMapper userMapper;

    /**
     * 拦截用户是否是登录状态
     * 目标资源执行前执行的方法，如果返回true表示目标方法可以被执行
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取cookie中的用户Id
        Integer userId = LoginUserUtil.releaseUserIdFromCookie(request);
        // 判断用户Id是否为空，且数据库中存在该Id的用户记录
        if (userId == null || userMapper.selectById(userId) == null) {
            // 抛出未登录异常
            throw new NoLoginException();
        }
        return true;
    }
}
